# src/crud/sys_message.py
from typing import List, Optional
from sqlalchemy.orm import Session
from src.models import sys_message as models
from src.schemas import sys_message as schemas, request_model
from src.core import retMes, str_utils as strU, orm_curd
from src.schemas.login_manager import AuthManager
from src.crud import sys_api_project as SysApiProjectCRUD
from src.core.config import Config



# ---------------------- 单条新增 ----------------------
def create_message(db: Session,
                   auth: AuthManager,
                   msg: schemas.SysMessageCreate) -> dict:
    """
    新增单条语言消息。
    内部调用 create_messages 保持行为一致。
    """
    return orm_curd.Insert(
        db,
        auth,
        models.SysMessage,
        schemas.SysMessageInDB,
        "语言消息",
        [msg.dict()],
        ["api_id", "language", "code"],  # 业务唯一键
        skip_duplicates=True
    )


# ---------------------- 批量新增 ----------------------
def create_messages(db: Session,
                    auth: AuthManager,
                    messages: List[schemas.SysMessageCreate]) -> dict:
    """
    批量新增语言消息。
    """
    return orm_curd.Insert(
        db,
        auth,
        models.SysMessage,
        schemas.SysMessageInDB,
        "语言消息",
        messages,
        ["api_id", "language", "code"],
        skip_duplicates=True
    )


# ---------------------- 分页查询 ----------------------
def get_messages(db: Session,
                 auth: AuthManager,
                 page: int = 0,
                 page_size: int = 100,
                 FilterModel: Optional[request_model.QueryModel] = None,
                 id: Optional[str] = None) -> dict:
    """
    分页查询语言消息列表。
    """
    return orm_curd.query_with_page(
        db,
        auth,
        models.SysMessage,
        schemas.SysMessageInDB,  # 如需原始对象可传 None
        id=id,
        filter_model=FilterModel,
        page=page,
        page_size=page_size
    )


# ---------------------- 单条更新 ----------------------
def update_message(db: Session,
                   auth: AuthManager,
                   msg_id: str,
                   msg: schemas.SysMessage) -> schemas.SysMessage:
    """
    更新单条语言消息。
    """
    update_model = request_model.UpdateModel([
        request_model.UpdateItem(
            pk_names=["id"],
            pk_values=[msg_id],
            data=msg.dict(exclude_unset=True)
        )
    ])
    return orm_curd.update(
        db,
        auth,
        models.SysMessage,
        update_model
    )


# ---------------------- 批量更新 ----------------------
def update_messages(db: Session,
                    auth: AuthManager,
                    updateModel: request_model.UpdateModel) -> dict:
    """
    批量更新语言消息。
    """
    return orm_curd.update(
        db,
        auth,
        models.SysMessage,
        updateModel
    )


# ---------------------- 删除 ----------------------
def delete_messages(db: Session,
                    auth: AuthManager,
                    deleteModel: request_model.DeleteModel) -> dict:
    """
    删除语言消息（硬删除）。
    """
    return orm_curd.delete(
        db=db,
        auth=auth,
        model_cls=models.SysMessage,
        delete_obj=deleteModel
    )


def ini_msg_exists(db: Session, api_id: str, language: str, code: int) -> bool:
    return db.query(models.SysMessage).filter(
        models.SysMessage.api_id == api_id,
        models.SysMessage.language == language,
        models.SysMessage.code == code,
        models.SysMessage.deletion_mark == 0
    ).first() is not None


def ini_create_message(db: Session, project: schemas.SysMessageCreate):
    db_message = models.SysMessage(**project.dict())
    db.add(db_message)
    db.commit()
    db.refresh(db_message)
    return db_message


def ini_message(db: Session):
    """
    初始化语言消息。
    """
    # 1. 按语言分层
    LANGUAGES = Config.MESSAGE_LANGUAGES
    MESSAGE_CONTENT_JSON=Config.MESSAGE_CONTENT_JSON
    messages = MESSAGE_CONTENT_JSON.get('messages', {})
    messagesNoAPI = MESSAGE_CONTENT_JSON.get('messagesNoAPI', {}) # json.loads(Config.MESSAGE_NO_API_KEY_CONTENT)
    sysApiProjects = SysApiProjectCRUD.ini_get_api_project_by_api_code(db, None)
    for sysApiProject in sysApiProjects:
        api_id = sysApiProject.id
        for lang in LANGUAGES: # ["zh", "en", "fr", "zh-TW"]:
            lang_dict = messages.get(lang, {})
            for code, item in lang_dict.items():
                msg = item["message"]
                desc = item["desc"]
                if not ini_msg_exists(db, api_id, lang, code):
                    ini_create_message(db, schemas.SysMessageCreate(api_id=api_id,
                                                                    language=lang,
                                                                    code=code,
                                                                    message=msg,
                                                                    description=desc
                                                                    ))

    api_id = "-1"
    for lang in LANGUAGES:  # ["zh", "en", "fr", "zh-TW"]:
        lang_dict = messagesNoAPI.get(lang, {})
        for code, item in lang_dict.items():
            msg = item["message"]
            desc = item["desc"]
            if not ini_msg_exists(db, api_id, lang, code):
                ini_create_message(db, schemas.SysMessageCreate(api_id=api_id,
                                                                language=lang,
                                                                code=code,
                                                                message=msg,
                                                                description=desc
                                                                ))
